#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
清算 - 消息通知解析功能使用示例
"""

import os
import sys

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from examples.base_example import BaseExample
from jlpay.services.clearing_service import ClearingService


class MsgNotifyExample(BaseExample):
    """消息通知解析示例类"""
    
    def __init__(self):
        """初始化示例类"""
        super().__init__("examples.clearing.notify")
        # 通知解析不需要配置，重新创建ClearingService实例
        self.clearing_service = ClearingService(None)
    
    def build_notify_data(self):
        """构建通知数据"""
        # 模拟接收到的通知数据
        notify_data = {
            "merch_no": "84944035812S123",
            "settle_type": "T0",
            "amount": "2000",
            "fee_amount": "300",
            "out_settle_id": "191912345678901894",
            "settle_id": "411109630795649800601630",
            "postscript": "postscript",
            "payment_time": "2024-02-21 14:50:22",
            "org_no": "123456",
            "result_state": "SUCCESS"
        }
        return notify_data
    
    def demo(self):
        """执行通知消息解析示例"""
        self.logger.info("开始执行通知消息解析示例")
        
        # 构建通知数据
        notify_data = self.build_notify_data()
        
        # 解析通知消息
        try:
            notify_dto = self.clearing_service.parse_notify(notify_data)
            
            if notify_dto:
                self.logger.info("通知消息解析成功！")
                self.logger.info(f"商户号：{notify_dto.merch_no}")
                self.logger.info(f"结算类型：{notify_dto.settle_type}")
                self.logger.info(f"金额：{notify_dto.amount}")
                self.logger.info(f"手续费：{notify_dto.fee_amount}")
                self.logger.info(f"外部结算ID：{notify_dto.out_settle_id}")
                self.logger.info(f"结算ID：{notify_dto.settle_id}")
                self.logger.info(f"附言：{notify_dto.postscript}")
                self.logger.info(f"付款时间：{notify_dto.payment_time}")
                self.logger.info(f"机构号：{notify_dto.org_no}")
                self.logger.info(f"结果状态：{notify_dto.result_state}")
            else:
                self.logger.error("通知消息解析失败")
                
        except Exception as e:
            self.logger.error(f"通知消息解析异常: {str(e)}")
        
        self.logger.info("通知消息解析示例执行完毕")


if __name__ == "__main__":
    logger = MsgNotifyExample().logger
    logger.info("==================================================")
    logger.info("===== 通知消息解析示例 开始 =====")
    logger.info("==================================================")
    
    example = MsgNotifyExample()
    example.demo()
    
    logger.info("==================================================")
    logger.info("===== 通知消息解析示例执行完毕 =====")
    logger.info("==================================================") 